package com.sugon.controller;

import com.alibaba.fastjson.JSON;
import com.sugon.Application;
import com.sugon.service.VideoService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * @description:
 * @author: jichenglu
 * @create: 2019-09-03 14:51
 **/

@RestController
@RequestMapping(value="/video")
public class VideoController {

    @Autowired
    private VideoService videoService;

    @Value("${ffmpeg.thread}")
    private int thread;

    @Value("${ffmpeg.network}")
    private String network;

    /**
     * rtsp转rtmp
     * @param rtspUrl
     * @return
     * @throws Exception
     */
    @CrossOrigin
    @ApiOperation("获取rtmp地址")
    @RequestMapping(value="/getRtmpUrl")
    public Object getRtmpUrl(@RequestBody String rtspUrl) throws Exception{
        if(rtspUrl.contains("\"")){
            rtspUrl = JSON.parse(rtspUrl).toString();
            //rtspUrl = JSON.parseObject(rtspUrl).getString("rtspUrl");
        }
        if(Application.urlMap.get(rtspUrl) != null){
            String rtmpUrl = Application.urlMap.get(rtspUrl);
            //如果有公网映射，就把内网改成公网
            if(network != null && network.contains("rtmp://")){
                String[] strs = rtmpUrl.split("/");
                String str = strs[strs.length-1];
                rtmpUrl = network + str;
            }
            System.out.println("实际地址:" + rtmpUrl);
            return JSON.toJSONString(rtmpUrl);
        }
        //大于最大线程数移除第一个数据
        if(Application.urlMap.size() >= thread){
            String key = Application.urlMap.entrySet().stream().findFirst().get().getKey();
            String value = Application.urlMap.entrySet().stream().findFirst().get().getValue();
            Application.urlMap.remove(key);
            String[] strs = value.split("/");
            String str = strs[strs.length-1];
            videoService.stopFfmpeg(str);
        }
        String rtmpUrl = videoService.getRtmpUrl(rtspUrl);
        Application.urlMap.put(rtspUrl,rtmpUrl);
        //如果有公网映射，就把内网改成公网
        if(network != null && network.contains("rtmp://")){
            String[] strs = rtmpUrl.split("/");
            String str = strs[strs.length-1];
            rtmpUrl = network + str;
        }
        System.out.println("实际地址:" + rtmpUrl);
        return JSON.toJSONString(rtmpUrl);
    }

    @ApiOperation("暂停播放")
    @PostMapping(value="/stopFfmpeg")
    public Object stopFfmpeg(@RequestBody String key){
        if(key.contains("\"")){
            key = JSON.parse(key).toString();
        }
        int k = videoService.stopFfmpeg(key);
        return JSON.toJSON(k);
    }

}
